<template>
  <div class="company-review-container">
    <div class="company-review-content">
      <!-- 搜索条件 -->
      <el-form 
        ref="searchFormRef"
        :model="searchForm" 
        class="search-form"
        inline
      >
        <el-input 
          v-model="searchForm.companyName" 
          placeholder="企业名称"
          clearable
          style="width: 200px"
        />
        
        <el-date-picker
          v-model="searchForm.commitDateStart"
          type="date"
          placeholder="开始日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 150px"
        />
        <span class="date-separator">至</span>
        <el-date-picker
          v-model="searchForm.commitDateEnd"
          type="date"
          placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 150px"
        />
        
        <el-select 
          v-model="searchForm.reviewStatus" 
          placeholder="审核状态"
          clearable
          style="width: 150px"
        >
          <el-option label="未发起" :value="0" />
          <el-option label="通过" :value="1" />
          <el-option label="失败" :value="2" />
          <el-option label="审核中" :value="3" />
        </el-select>
        
        <el-button type="primary" @click="handleSearch" :loading="loading">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </el-form>
      
      <!-- 数据列表 -->
      <div class="table-header">
        <h3>审核列表</h3>
        <div class="table-actions">
          <el-button type="primary" text @click="refreshData" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
      
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          stripe
          style="width: 100%"
          max-height="500"
          size="small"
        >
          <el-table-column prop="logo" label="企业Logo" width="80" align="center">
            <template #default="{ row }">
              <el-avatar 
                :src="row.logo" 
                :size="40"
                class="company-logo"
              />
            </template>
          </el-table-column>
          
          <el-table-column label="企业信息" min-width="250">
            <template #default="{ row }">
              <div class="company-details">
                <div class="company-name">{{ row.companyName }}</div>
                <div class="company-short">{{ row.shortName }}</div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="审核状态" width="100">
            <template #default="{ row }">
              <el-tag 
                :type="getStatusType(row.reviewStatus)"
                size="small"
              >
                {{ getStatusText(row.reviewStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="commitDate" label="申请日期" width="120" />
          
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                text 
                size="small"
                @click="handleReview(row)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="searchForm.pageNo"
            v-model:page-size="searchForm.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :pager-count="5"
            prev-text="上一页"
            next-text="下一页"
            small
          />
        </div>
      </div>
    </div>
    
    <!-- 审核详情侧边弹窗 -->
    <el-drawer
      v-model="drawerVisible"
      title="审核详情"
      direction="rtl"
      size="600px"
      :before-close="handleCloseDrawer"
    >
      <div v-if="reviewDetail" class="review-detail">
        <div class="company-basic-info">
          <h4>企业基本信息</h4>
          <div class="info-item">
            <span class="label">企业名称：</span>
            <span class="value">{{ reviewDetail.companyName }}</span>
          </div>
          <div class="info-item">
            <span class="label">企业简称：</span>
            <span class="value">{{ reviewDetail.shortName }}</span>
          </div>
          <div class="info-item">
            <span class="label">所在行业：</span>
            <span class="value">{{ reviewDetail.industry }}</span>
          </div>
          <div class="info-item">
            <span class="label">企业规模：</span>
            <span class="value">{{ reviewDetail.peopleSize }}</span>
          </div>
          <div class="info-item">
            <span class="label">申请日期：</span>
            <span class="value">{{ reviewDetail.commitDate }}</span>
          </div>
          <div class="info-item">
            <span class="label">审核状态：</span>
            <span class="value">
              <el-tag :type="getStatusType(reviewDetail.reviewStatus)" size="small">
                {{ getStatusText(reviewDetail.reviewStatus) }}
              </el-tag>
            </span>
          </div>
        </div>
        
        <div class="company-images">
          <h4>企业资质</h4>
          <div class="image-item">
            <span class="label">企业Logo：</span>
            <el-image
              :src="reviewDetail.logo"
              :preview-src-list="[reviewDetail.logo]"
              fit="cover"
              style="width: 100px; height: 100px; border-radius: 8px; cursor: pointer;"
              preview-teleported
            />
          </div>
          <div class="image-item">
            <span class="label">营业执照：</span>
            <el-image
              :src="reviewDetail.bizLicense"
              :preview-src-list="[reviewDetail.bizLicense]"
              fit="cover"
              style="width: 200px; height: 120px; border-radius: 8px; cursor: pointer;"
              preview-teleported
            />
          </div>
        </div>
        
        <!-- 已审核状态显示 -->
        <div v-if="reviewDetail.reviewStatus === 1 || reviewDetail.reviewStatus === 2" class="review-result">
          <h4>审核结果</h4>
          <div class="info-item">
            <span class="label">审核意见：</span>
            <span class="value">{{ reviewDetail.reviewReplay || '无' }}</span>
          </div>
          <div class="info-item">
            <span class="label">审核人：</span>
            <span class="value">{{ reviewDetail.reviewUserName || '未知' }}</span>
          </div>
          <div class="status-message">
            <el-alert
              :title="reviewDetail.reviewStatus === 1 ? '该审核已通过' : '该审核已被拒绝'"
              :type="reviewDetail.reviewStatus === 1 ? 'success' : 'error'"
              show-icon
              :closable="false"
            />
          </div>
        </div>
        
        <!-- 待审核状态显示 -->
        <div v-if="reviewDetail.reviewStatus === 3" class="review-actions">
          <h4>审核操作</h4>
          <div class="review-form">
            <el-form :model="reviewForm" label-width="80px">
              <el-form-item label="审核意见">
                <el-input
                  v-model="reviewForm.reviewReplay"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入审核意见"
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>
              <el-form-item label="审核人">
                <el-input
                  v-model="reviewForm.reviewUserName"
                  placeholder="请输入审核人姓名"
                  maxlength="50"
                />
              </el-form-item>
              <el-form-item label="审核结果">
                <el-switch
                  v-model="reviewForm.isApproved"
                  active-text="通过"
                  inactive-text="拒绝"
                  active-color="#67c23a"
                  inactive-color="#f56c6c"
                />
              </el-form-item>
            </el-form>
            <div class="action-buttons">
              <el-button type="primary" @click="handleSubmitReview" :loading="submitLoading">
                提交审核
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getCompanyReviewListApi, getCompanyReviewDetailApi, submitCompanyReviewApi } from '@/api/enterprise'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const drawerVisible = ref(false)
const reviewDetail = ref(null)
const submitLoading = ref(false) // 新增：提交审核时的加载状态

// 审核表单
const reviewForm = reactive({
  reviewReplay: '',
  reviewUserName: '',
  isApproved: true // 默认选择通过
})

// 搜索表单
const searchForm = reactive({
  companyName: '',
  commitDateStart: '',
  commitDateEnd: '',
  reviewStatus: null,
  pageNo: 1,
  pageSize: 10
})

// 表单引用
const searchFormRef = ref()

// 计算属性
const canSearch = computed(() => {
  return searchForm.companyName || searchForm.commitDateStart || searchForm.commitDateEnd || searchForm.reviewStatus !== null
})

// 方法
const getStatusType = (status) => {
  const statusMap = {
    0: 'info',
    1: 'success',
    2: 'danger',
    3: 'warning'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    0: '未发起',
    1: '通过',
    2: '失败',
    3: '审核中'
  }
  return statusMap[status] || '未知'
}

const handleSearch = async () => {
  searchForm.pageNo = 1
  await fetchData()
}

const handleReset = () => {
  searchFormRef.value?.resetFields()
  searchForm.companyName = ''
  searchForm.commitDateStart = ''
  searchForm.commitDateEnd = ''
  searchForm.reviewStatus = null
  searchForm.pageNo = 1
  searchForm.pageSize = 10
  fetchData()
}

const handleSizeChange = (size) => {
  searchForm.pageSize = size
  searchForm.pageNo = 1
  fetchData()
}

const handleCurrentChange = (page) => {
  searchForm.pageNo = page
  fetchData()
}

const handleReview = async (row) => {
  try {
    loading.value = true
    // 调用API获取审核详情
    const response = await getCompanyReviewDetailApi(row.id)
    reviewDetail.value = response
    drawerVisible.value = true
  } catch (error) {
    console.error('获取审核详情失败:', error)
    ElMessage.error('获取审核详情失败')
  } finally {
    loading.value = false
  }
}

const handleCloseDrawer = () => {
  drawerVisible.value = false
  reviewDetail.value = null
  // 清空审核表单
  reviewForm.reviewReplay = ''
  reviewForm.reviewUserName = ''
  reviewForm.isApproved = null // 清空审核结果开关
}

const handleSubmitReview = async () => {
  if (!reviewForm.reviewReplay.trim()) {
    ElMessage.warning('请输入审核意见')
    return
  }
  if (!reviewForm.reviewUserName.trim()) {
    ElMessage.warning('请输入审核人姓名')
    return
  }

  try {
    submitLoading.value = true
    
    // 构建提交审核的数据结构
    const params = {
      id: reviewDetail.value.id,
      companyName: reviewDetail.value.companyName,
      shortName: reviewDetail.value.shortName,
      logo: reviewDetail.value.logo,
      bizLicense: reviewDetail.value.bizLicense,
      industry: reviewDetail.value.industry,
      peopleSize: reviewDetail.value.peopleSize,
      reviewStatus: reviewForm.isApproved ? 1 : 2, // 1: 通过, 2: 失败
      reviewReplay: reviewForm.reviewReplay,
      reviewUserName: reviewForm.reviewUserName
    }
    
    await submitCompanyReviewApi(params)
    ElMessage.success('审核提交成功')
    handleCloseDrawer()
    fetchData() // 刷新列表
  } catch (error) {
    console.error('提交审核失败:', error)
    ElMessage.error('提交审核失败')
  } finally {
    submitLoading.value = false
  }
}

const refreshData = () => {
  fetchData()
}

const fetchData = async () => {
  try {
    loading.value = true
    
    // 过滤空值
    const params = {}
    Object.keys(searchForm).forEach(key => {
      if (searchForm[key] !== '' && searchForm[key] !== null && searchForm[key] !== undefined) {
        params[key] = searchForm[key]
      }
    })
    
    const response = await getCompanyReviewListApi(params)
    
    if (response && response.list) {
      tableData.value = response.list
      total.value = response.totals || 0
    } else {
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取企业审核列表失败:', error)
    ElMessage.error('获取数据失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.company-review-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
}



.company-review-content {
  background: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  min-height: calc(100vh - 120px);
  
  .search-form {
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
    
    .date-separator {
      margin: 0 5px;
      color: #909399;
    }
  }
  
  .table-header {
    margin-bottom: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h3 {
      margin: 0;
      color: #303133;
      font-size: 16px;
    }
  }
  
  .table-container {
    display: flex;
    flex-direction: column;
    min-height: 600px;
    
    .el-table {
      flex: 1;
      margin-bottom: 0;
      width: 100%;
      overflow-x: auto;
      
      .el-table__body-wrapper {
        overflow-x: auto;
      }
      
      .company-logo {
        display: block;
        margin: 0 auto;
      }
      
      .company-details {
        .company-name {
          font-weight: 500;
          color: #303133;
          margin-bottom: 2px;
          font-size: 14px;
        }
        
        .company-short {
          font-size: 12px;
          color: #909399;
        }
      }
    }
    
    .pagination-container {
      display: flex;
      justify-content: center;
      padding: 15px 0;
      margin-top: 15px;
      border-top: 1px solid #f0f0f0;
      flex-shrink: 0;
      
      .el-pagination {
        flex-wrap: wrap;
        justify-content: center;
        min-width: 0;
        
        .el-pagination__total,
        .el-pagination__sizes,
        .el-pagination__jump {
          margin: 0 8px;
        }
        
        .el-pager {
          margin: 0 8px;
        }
      }
    }
  }
}

.review-detail {
  padding: 20px;
  
  .company-basic-info,
  .company-images,
  .review-actions {
    margin-bottom: 30px;
    
    h4 {
      margin: 0 0 15px 0;
      color: #303133;
      font-size: 16px;
      border-bottom: 2px solid #409eff;
      padding-bottom: 8px;
    }
  }
  
  .info-item {
    display: flex;
    margin-bottom: 12px;
    
    .label {
      width: 100px;
      color: #606266;
      font-weight: 500;
    }
    
    .value {
      color: #303133;
      flex: 1;
    }
  }
  
  .image-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    
    .label {
      width: 100px;
      color: #606266;
      font-weight: 500;
      margin-right: 15px;
    }
  }
  
  .action-buttons {
    display: flex;
    gap: 15px;
    justify-content: center;
  }
  
  .review-result {
    .status-message {
      margin-top: 15px;
    }
  }
  
  .review-actions {
    .review-form {
      margin-bottom: 20px;
      
      .el-form-item {
        margin-bottom: 15px;
      }
    }
  }
}

// 响应式处理
@media (max-width: 1200px) {
  .company-review-content {
    .search-form {
      .el-form-item {
        margin-bottom: 15px;
      }
    }
    
    .pagination-container {
      .el-pagination {
        .el-pagination__total,
        .el-pagination__sizes,
        .el-pagination__jump {
          margin: 0 4px;
        }
        
        .el-pager {
          margin: 0 4px;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .company-review-content {
    padding: 15px;
    
    .search-form {
      .el-form-item {
        display: block;
        margin-bottom: 15px;
        
        .el-form-item__label {
          display: block;
          margin-bottom: 8px;
        }
      }
    }
    
    .pagination-container {
      .el-pagination {
        flex-direction: column;
        gap: 10px;
        
        .el-pagination__total,
        .el-pagination__sizes,
        .el-pagination__jump {
          margin: 0;
        }
        
        .el-pager {
          margin: 0;
        }
      }
    }
  }
}


</style>
